<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\model\Coupon as couponModel;
use Think\Db;
class Coupon extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];

    public function CouponList()
    {
        $coupon = new couponModel();
        $list = $coupon
        ->alias('a')
        ->join('user_coupon b','a.id = b.cid and b.uid = '.$this->uid,'LEFT')
        ->field('a.*')
        ->where([
            'starttime' => ['<',time()],
            'endtime' => ['>',time()],
            'b.status' => ['EXP',Db::raw('IS NULL')],
        ])
        ->select();
        $data = [
            'list' => $list,
            'image'=>Config('site.image'),
        ];
        $this->ajaxSuccess($data);
    }
    //领取优惠券
    public function receive(){
        $uid = $this->uid;
        $cid = input('cid');
        $coupon = new couponModel();
        $couponInfo = $coupon->where(['id'=>$cid])->find();
        if(!$couponInfo)$this->ajaxError('优惠券ID错误');
        $isReceive = db('user_coupon')->where(['uid'=>$uid,'cid'=>$cid])->find();
        if($isReceive){
            $this->ajaxError('请勿重复领取');
        }
        db('user_coupon')->insert([
            'uid'=>$uid,
            'cid'=>$cid,
        ]);
        $this->ajaxSuccess();
    }
    //已领取的优惠券接口
    public function getReceived(){
        $uid = $this->uid;
        $couponList = db('user_coupon')
        ->alias('a')
        ->join('coupon b','a.cid = b.id')
        ->where([
            'a.uid' => ['eq',$uid],
            'b.starttime' => ['<',time()],
            'b.endtime' => ['>',time()],
            'a.status' =>['eq',1]
        ])
        ->field("b.id,b.name,b.use_price,b.cut_price,FROM_UNIXTIME(b.starttime,'%Y-%m-%d') as starttime,FROM_UNIXTIME(b.endtime,'%Y-%m-%d') as endtime")
        ->select();
        $this->ajaxSuccess($couponList);
    }

}
